<script setup lang="ts">
import {
  reportShelfWrongDataList,
  workOrderHandadd,
  workOrderAdd,
  tenOptions,
} from "@/api/order/index";

import { ElMessage, ElMessageBox } from "element-plus";
import { computed, onMounted, ref } from "vue";
import useUserStore from "@/store/modules/user";
let useStore = useUserStore();
const hasRole = (role: any) => {
  return useStore.user.roles.includes(role);
};

const libraryList = ref([] as any[]); //列表数据
const queryFormRef = ref(); //refForm
const tenn = ref([] as any);
const total = ref();
const loading = ref(false);
let queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  taskNo: "",
} as any);
// const resetQuery = () => {

// };
/**
 * 列表数据
 */
const getList = async () => {
  if (queryParams.value.taskNo == "" || !queryParams.value.taskNo) {
    ElMessage.warning("任务编号不能为空");
    return;
  }
  queryParams.value.taskNo = queryParams.value.taskNo;
  const res = await reportShelfWrongDataList(queryParams.value);
  libraryList.value = res.data.records!;
  total.value = res.data.total;
  // console.log(res, "分页列表");
  //console.log(queryParams.value, "列表");
};
/**
 * 列表数据
 */
const Options = async () => {
  const res = await tenOptions(useStore.encryptedData);
  tenn.value = res.data;
  // console.log(res, "10分页列表");

  // console.log(res.data.list, "分页列表");
  // console.log(queryParams.value);
};

// const isSearchDisabled = computed(() => {
//   return !selectedRows.value;
// });

onMounted(() => {
  // getList();
  Options();
});
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val;
  queryParams.value.pageNum = 1;

  getList();
};
const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val;
  getList();
  window.scrollTo({ top: 0, behavior: "smooth" }); // 立即回到顶部，并使用平滑滚动效果
};
const Status = (status: number) => {
  const STATUSES = [
    { id: 0, name: "未处理 " },
    { id: 1, name: "已处理" },
    { id: 2, name: "在还书箱上" },
  ];
  const matched = STATUSES.find((item) => item.id === status);
  return matched ? matched.name : "";
};
const selectedRows = ref([] as any); // 存储用户选择的行
// 处理选择的行
const handleSelectionChange = (selection: any) => {
  selectedRows.value = selection;
};
// 手动处理按钮点击事件
const handleManualProcess = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要处理的行");
    return;
  }
  ElMessageBox.confirm("确定要手动处理选中的行吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      // 在这里处理手动处理的逻辑
      // 获取选中行的 id
      const selectedIds = selectedRows.value.map((row: any) => row.id);
      //console.log("选中的行 id：", selectedIds);
      // console.log(selectedRows.value, "selectedRows.value");
      const res = await workOrderHandadd(selectedIds);
      // console.log(res, "Res");
      if (res.code == 200) {
        ElMessage.success("手动处理成功");
        getList();
        selectedRows.value = [];
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {
      // ElMessage.info("已取消手动处理");
    });
};

// 生成工单按钮点击事件
const handleGenerateOrder = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要生成工单的行");
    return;
  }

  ElMessageBox.prompt("请输入工单名称", "生成工单", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /^[\s\S]{1,50}$/, // 允许1-50个任意字符
    inputErrorMessage: "工单名称不能为空且长度不能超过50个字符",
  })
    .then(async ({ value }) => {
      const workName = value?.trim();
      if (!workName) {
        ElMessage.warning("工单名称不能为空");
        return;
      }

      const selectedIds = selectedRows.value.map((row: any) => row.id);

      try {
        const res = await workOrderAdd(
          selectedIds,
          queryParams.value.taskNo,
          workName // 新增的第三个参数
        );

        if (res.code === 200) {
          ElMessage.success("工单生成成功");
          getList();
          selectedRows.value = [];
        } else {
          ElMessage.error(res.msg || "操作失败");
        }
      } catch (error) {
        ElMessage.error("请求失败，请检查网络连接");
      }
    })
    .catch(() => {
      // 用户取消操作不需要处理
    });
};
</script>

<template>
  <div class="app-container">
    <div class="search">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="任务编号">
          <el-select
            style="width: 190px"
            clearable
            v-model="queryParams.taskNo"
            filterable
            allow-create
            default-first-option
            placeholder="请选择或盘点任务编号"
          >
            <el-option
              v-for="item in tenn"
              :key="item.label"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工单编号">
          <el-input
            clearable
            v-model="queryParams.workNo"
            placeholder="请输入工单编号"
          />
        </el-form-item>
        <el-form-item label="还书点">
          <el-select
            style="width: 190px"
            clearable
            v-model="queryParams.markerSame"
            placeholder="请选择还书点"
          >
            <el-option label="相同" value="1" />
            <el-option label="不同" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="正确位置">
          <el-input
            clearable
            v-model="queryParams.shouldShelf"
            placeholder="请输入正确位置"
          />
        </el-form-item>
        <el-form-item label="错架位置">
          <el-input
            clearable
            v-model="queryParams.realShelf"
            placeholder="请输入错架位置"
          />
        </el-form-item>

        <el-form-item label="图书状态">
          <el-select
            clearable
            style="width: 190px"
            v-model="queryParams.bookStatus"
            allow-create
            default-first-option
            placeholder="请选择图书状态"
          >
            <el-option label="未处理" value="0" />
            <el-option label="已处理" value="1" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getList">搜索</el-button>
          <!-- <el-button @click="resetQuery"><i-ep-refresh />重置</el-button> -->
        </el-form-item>
      </el-form>
    </div>
    <el-card>
      <template #header>
        <el-button type="success" @click="handleManualProcess"
          >手动处理</el-button
        >
        <el-button type="success" @click="handleGenerateOrder"
          >生成工单</el-button
        >
      </template>
      <el-table
        v-loading="loading"
        :data="libraryList"
        :border="true"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="盘点任务编号" prop="taskNo" :align="'center'" />
        <el-table-column label="图书编号" prop="bookCode" :align="'center'" />

        <el-table-column label="图书名称" prop="bookName" :align="'center'" />
        <el-table-column
          label="应在书架"
          prop="shouldShelf"
          :align="'center'"
        />
        <el-table-column label="实在书架" prop="realShelf" :align="'center'" />
        <el-table-column
          label="应在书架还书点位"
          prop="shouldReturnMarker"
          :align="'center'"
          width="140"
        />
        <el-table-column
          label="实在书架还书点位"
          prop="realReturnMarker"
          :align="'center'"
          width="140"
        />
        <el-table-column label="工单编号" prop="workNo" :align="'center'" />
        <el-table-column label="rfid" prop="rfid" :align="'center'" />
        <el-table-column label="还书箱位置" prop="position" :align="'center'" />
        <el-table-column label="图书状态" prop="bookStatus" :align="'center'">
          <template #default="{ row }"> {{ Status(row.bookStatus) }}</template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="total > 0"
        style="margin-top: 15px"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
* {
  list-style: none;
}

el-select {
  padding-bottom: 100px;
}
</style>
